<?php
/**
 * 主控制器
 *
 * @package		Hooloo framework
 * @author 		Bill
 * @copyright 	Hooloo Co.,Ltd
 * @version		1.0
 * @release		2017.05.08
 */
//if(!defined('BASEPATH')) exit('No direct script access allowed');

class Controller{
    protected $_controller; //控制器名
    protected $_action; //方法名
    protected $_module; //分组名
    protected $db; //mysql数据库
    protected $ip;//用户ip地址
    protected $config_sys; //系统配置
    protected $_data; //模板数据

    public function __construct(){
        $this->_controller = strtolower($GLOBALS['controller']);
        $this->_action = strtolower($GLOBALS['action']);
        $this->_module = strtolower($GLOBALS['module']);

        //用户ip地址
        $this->ip = get_client_ip();

        //查询记录
        // $sql = "SELECT * FROM `ip_lib` where ip1  {$this->ip} <= ip2;";
        // $row = $this->db->query($sql)->row_array();
        //$country = isset($row["country"]) ? $row["country"] : "中国";

        //屏蔽恶意ip地址
        if (($this->ip >= 599458049 && $this->ip <= 599458303) 		// 美国 35.187.1.1 ~ 35.187.1.255
            || ($this->ip >= 704349697 && $this->ip <= 704349951)		// 摩洛哥 41.251.134.1 ~ 41.251.134.255
            || ($this->ip >=  599793153 && $this->ip <= 599793407)      // 美国 Merit网络公司 35.192.30.1 ~ 35.192.30.255
            || ($this->ip >=  3386765313 && $this->ip <= 3386765567)   	// 巴拿马 201.221.240.1 ~ 201.221.240.255
            || ($this->ip >=  1778547969 && $this->ip <= 1778548223)   	// 浙江省杭州市 网易计算机系统BGP节点 106.2.125.1 ~ 106.2.125.255
            || ($this->ip >=  600124673 && $this->ip <= 600124927)   	// 美国 Merit网络公司 35.197.45.1 ~ 35.197.45.255
            || ($this->ip >=  600140289 && $this->ip <= 600140543)   	// 美国 Merit网络公司 35.197.106.1 ~ 35.197.106.255
            || ($this->ip >=  917447169 && $this->ip <= 917447423)   	// 美国 华盛顿州西雅图市亚马逊(Amazon)公司数据中心 54.175.34.1 ~ 54.175.34.255
            || ($this->ip >=  1757791489 && $this->ip <= 1757791743)   	// 美国 谷歌公司云数据中心 104.197.197.1 ~ 104.197.197.255
            || ($this->ip >=  794585089 && $this->ip <= 794585343)   	// 加拿大 47.92.104.1 ~ 47.92.104.255
            || ($this->ip >=  1754928385 && $this->ip <= 1754928639)   	// 美国 谷歌公司云数据中心 104.154.21.1 ~ 104.154.21.255
            || ($this->ip >=  2945446913 && $this->ip <= 2945447167)   	// 马来西亚 吉隆坡 175.143.244.1 ~ 175.143.244.255
            || ($this->ip >=  1757741825 && $this->ip <= 1757742079)   	// 美国 谷歌公司云数据中心 104.197.3.1 ~ 104.197.3.255
            || ($this->ip >=  1330358017 && $this->ip <= 1330358271)   	// 美国 79.75.167.1 ~ 79.75.167.255
            || ($this->ip >=  1020508161 && $this->ip <= 1020508415)   	// 山东省济宁市 联通 60.211.184.1 ~ 60.211.184.255
            || ($this->ip >=  3572305665 && $this->ip <= 3572305919)   	// 丹麦 212.237.15.1 ~ 212.237.15.255
            || ($this->ip >=  1135036417 && $this->ip <= 1135036671)   	// 美国 新泽西州伯灵顿县月桂山乡Comcast有线通信股份有限公司 67.167.72.1 ~ 67.167.72.255
            || ($this->ip >=  1731930625 && $this->ip <= 1731930879)   	// 广东省深圳市 长城宽带 103.59.42.1 ~ 103.59.42.255
            || ($this->ip >=  1645404673 && $this->ip <= 1645404927)   	// 美国 98.18.226.1 ~ 98.18.226.255
            || ($this->ip >=  3031369729 && $this->ip <= 3031369983)   	// 上海市 电信 180.175.8.1 ~ 180.175.8.255
            || ($this->ip >=  3544741377 && $this->ip <= 3544741631)   	// 台湾省 中华电信(HiNet)
        ) {
            exit("系统错误，请稍后访问。");
        }

        //初始化数据库
        $this->init_db();
        $this->init_sys();

        if($this->_module == "admin"){
            $this->init_admin();
            if($this->_action != "get_system_time"){
                $this->init_admin_menu();
            }
        } elseif($this->_module == "home"){
            //自动执行不需要登录
            if ($this->_controller != "auto") {
                $this->init_user();
                if($this->_action != "get_system_time"){
                    $this->init_user_menu();
                }
            }
        } elseif ($this->_module == "agent") {
            $this->init_agent();
            if($this->_action != "get_system_time"){
                $this->init_admin_menu();
            }
        }

        //表单令牌
        $token = md5(date("Y-m-d H:i:s") . rand_code(6));
        $this->assign("token", $token);
    }

    public function __destruct (){
        //关闭数据库连接
        if($this->db){
            $this->db->close();
        }
    }

    /**
     * 初始化数据库
     * @param	int 	$server_id	服务器id	1-主服务器；2-从服务器
     */
    protected function init_db($server_id = 1){
        if(! $this->db){
            global $config;
            $db_config = $config['db_' . $server_id];
            $this->db = new Database();
            $this->db->connect($db_config['hostname'], $db_config['username'], $db_config['password'], $db_config['database']);
            $GLOBALS['db'] = $this->db;
        }
    }

    /**
     * 初始化系统配置
     */
    private function init_sys(){
        $cache = new Fcache();
        $sys = $cache->get("config_sys");
        if (! $sys) {
            //获取系统配置
            $sql  = "select id, name, value from config_sys";
            $config_sys = $this->db->query($sql)->result_array();
            $sys = array_column($config_sys, "value", "name");
            $cache->set("config_sys", $sys, 86400);
        }

        $GLOBALS['config_sys'] = $this->config_sys = $sys;
    }

    /**
     * 初始化用户登录
     */
    private function init_user(){
        //系统关闭状态0-关闭，1-开启
        if ($this->config_sys["system_switch"] == 0) {
            //系统关闭
            $this->assign("msg", $this->config_sys["system_switch_desc"]);
            $this->display("/public/close");
        }

        //判断浏览器是否是微信浏览器
        $openid = "";
        if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
            $openid = $this->init_openid();
        }

        if($this->_action != "verify"){
            if($this->_action == "login"){
                //防止用户重复登录
                if(isset($_SESSION["user"])){
                    //返回登录信息
                    IS_AJAX && ajax_return(0, "您已经登录");
                    redirect("/");
                }
            } else{
                // if ($openid = 'oEQ5jv43bJKU0EeWWFBmZArMkOUM') {

                // }
                //微信登录
                if (empty($_SESSION['openid']) == false) {
                    //查询用户信息
                    $sql = "select id, username, sex, nickname, realname, mobile, is_locked, is_stop, is_disable, try_times, last_try, password, atmpwd, demo_account, aid from user where openid = '$openid'";
                    $user = $this->db->query($sql)->row_array();
                    if ($user) {
                        $user["last_login"] = time();
                        //登录信息入session()
                        $_SESSION["user"] = $user;
                    }
                }

                //防止用户未登录
                if(! isset($_SESSION["user"])){
                    //返回登录信息
                    IS_AJAX && ajax_return(2, "您还未登录，请先登录");
                    redirect("/user/login");
                } else {
                    if (is_mobile() == false) {
                        //登录失效
                        $time = $_SESSION["user"]["last_login"];
                        if (time() - $time >= $this->config_sys["cookie_length"] * 3600) {
                            //更新在线状态
                            $sql = "update user set is_online = 0 where id = '" . $_SESSION["user"]["id"] . "'";
                            $this->db->query($sql);

                            unset($_SESSION["user"]);
                            IS_AJAX && ajax_return(2, "登录已失效，请重新登录");
                            redirect("/user/login");
                        }
                    }
                }
            }
        }
    }

    /**
     * 获取用户openid
     */
    private function init_openid() {
        if(empty($_SESSION['openid'])) {
            include_once(APPPATH . 'library/Wxpay.php');
            $jsApi = new JsApi_pub();
            if (! isset($_GET['code'])) {
                //触发微信返回code码
                $url = $jsApi->createOauthUrlForCode();
                Header("Location: $url");
            } else {
                //获取code码，以获取openid
                $_SESSION["openid"] = $openid = $jsApi->getOpenId($_GET['code']);
                if (! $openid) {
                    $this->error("获取异常，请联系管理员！");
                }
            }
        } else {
            $openid = $_SESSION['openid'];
        }
        return $openid;
    }


    /**
     * 初始化用户菜单
     */
    private function init_user_menu(){
        //获取系统信息
        $week=array("日","一","二","三","四","五","六");
        $common_info = array(
            'week' => date("Y-m-d") . " 星期" . $week[date("w")],
            'time' => date("H:i:s"),
            'module' => $this->_module,
            'controller' => $this->_controller,
            'action' => $this->_action
        );

        //查询公告
        $cache = new Fcache();
        $common = $cache->get("common");
        if (! $common) {
            $sql = "select content, add_time from news where status = 1 and type = 1 order by add_time desc limit 1";
            $new = $this->db->query($sql)->row_array();
            if ($new) {
                $common = "[ " . date("Y-m-d", $new["add_time"]) . " ] " . $new["content"];
                $cache->set("common", $common, 86400);
            } else {
                $common = "暂无公告";
            }
        }
        $common_info["common"] = $common;

        //手续费
        $common_info["bull_cost"] = $this->config_sys["bull_cost"];
        $common_info["sell_cost"] = $this->config_sys["sell_cost"];
        $common_info["save_cost"] = $this->config_sys["save_cost"];
        $common_info["save_day"] = $this->config_sys["save_day"];

        //休市、开市
        $common_info["holiday"] = get_holiday() == true ? "开市" : "休市";

        //选中状态
        $this->assign('common_info', $common_info);
    }

    /**
     * 初始化后台登录
     */
    private function init_admin(){
        if($this->_action == "login"){
            //防止用户重复登录
            if(isset($_SESSION["admin"])){
                //返回登录信息
                IS_AJAX && ajax_return(2, "您已经登录");
                redirect("/");
            }
        } else{
            //防止用户未登录
            if(! isset($_SESSION["admin"])){
                //返回登录信息
                IS_AJAX && ajax_return(2, "您还未登录，请先登录");
                redirect("/index/login");
            }
        }
    }

    /**
     * 初始化后台菜单
     */
    private function init_admin_menu (){
        //左侧菜单
        $arr_action = array (
            //系统首页
            101 => "index",

            //用户管理
            201 => "ratio",
            202 => "user",
            203 => "staff",
            204 => "agent",
            205 => "adm",

            //报表统计
            301 => "stock",

            //款项设置
            401 => "userbill",
            404 => "atm",

            //其他功能
            501 => "news",
            502 => "holiday",
            503 => "stockcode",
            506 => "message",
            507 => "message",
            508 => "sms",
            509 => "system",
            510 => "config",
            511 => "rule"
        );
        $arr_action = array_flip($arr_action);
        $controller = $arr_action[$this->_controller];

        if(isset($controller)){
            //限制开户管理员只能访问部分菜单
            $this->check_auth();

            $current = substr($controller, 0, 1);
            $current2 = $controller - $current * 100;
            //例外情况-一般情况是用一个控制器冲突
            if($this->_controller == "news" && $this->_action == "rule"){
                $current2 = 11;
            } elseif($this->_controller == "userbill" && $this->_action == "index"){
                $current2 = 2;
            } elseif($this->_controller == "message" && $this->_action == "mail"){
                $current2 = 6;
            } elseif($this->_controller == "message" && $this->_action == "money"){
                $current2 = 7;
            } elseif ($this->_controller == "stockcode" && $this->_action == "check") {
                $current2 = 5;
            }  elseif ($this->_controller == "stockcode" && $this->_action == "drxd") {
                $current2 = 4;
            } elseif ($this->_controller == "stock" && $this->_action == "bull") {
                $current2 = 1;
                $current = 3;
            } elseif ($this->_controller == "stock" && $this->_action == "sell") {
                $current2 = 2;
                $current = 3;
            } elseif ($this->_controller == "stock" && $this->_action == "trust") {
                $current2 = 3;
                $current = 3;
            } elseif ($this->_controller == "stock" && $this->_action == "hold") {
                $current2 = 4;
                $current = 3;
            } elseif ($this->_controller == "stock" && $this->_action == "gain") {
                $current2 = 5;
                $current = 3;
            } elseif ($this->_controller == "userbill" && $this->_action == "logs") {
                $current2 = 3;
            } elseif ($this->_controller == "userbill" && $this->_action == "charge_log") {
                $current2 = 5;
            }
        } else{
            $current = $current2 = 1;
        }

        //获取系统信息
        $week=array("日","一","二","三","四","五","六");
        $common_info = array(
            'week' => date("Y-m-d") . " 星期" . $week[date("w")],
            'time' => date("H:i:s"),
            'current' => $current,
            'current2' => $current2,
            'module' => $this->_module,
            'controller' => $this->_controller,
            'action' => $this->_action
        );

        //选中状态
        $this->assign('common_info', $common_info);
    }

    /**
     * 初始化后台登录
     */
    private function init_agent(){
        if($this->_action == "login"){
            //防止用户重复登录
            if(isset($_SESSION["agent"])){
                //返回登录信息
                IS_AJAX && ajax_return(2, "您已经登录");
                redirect("/");
            }
        } else{
            //防止用户未登录
            if(! isset($_SESSION["agent"])){
                //返回登录信息
                IS_AJAX && ajax_return(2, "您还未登录，请先登录");
                redirect("/index/login");
            }
        }
    }

    /**
     * 获取系统时间
     * @return 	array	 $result 	结果集：day-日期，time-时间，week-周X
     */
    public function get_system_info(){
        //休市、开市
        $result["holiday"] = get_holiday() == true ? "开市" : "休市";
        if($this->_module == "admin"){
            //获取站内信数量
            $sql = "select count(*) c from message where receiver = 0 and isread = 0";
            $message = $this->db->query($sql)->row_array();
            $result["message"] = $message["c"];
        } elseif($this->_module == "home"){
            $uid = $_SESSION["user"]["id"];
            $sql = "select count(*) c from message where receiver = $uid and isread = 0";
            $message = $this->db->query($sql)->row_array();
            $result["message"] = $message["c"];
            if ($result["holiday"] == "开市" || empty($_SESSION["zhishu"])) {
                //上证综合指数
                $url = "http://hq.sinajs.cn/list=s_sh000001";
                $str = file_get_contents($url);
                $str = iconv('GB2312//IGNORE', 'UTF-8', $str);
                $str = str_ireplace('var hq_str_s_sh000001="', "", $str);
                $str = str_ireplace('";', "", $str);
                $arr = explode(",", $str);
                if (round($arr[2], 2) < 0) {
                    $style = '<span class="xinsu-fontcolor-green">';
                } else {
                    $style = '<span class="xinsu-fontcolor-red">';
                }
                $zhishu = $arr[0] . '：' . $style . round($arr[1], 2) . '&nbsp;&nbsp;&nbsp;' . round($arr[2], 2) . '&nbsp;&nbsp;&nbsp;' . $arr[3] . '%</span>&nbsp;&nbsp;&nbsp;<span>' . round($arr[5] / 10000, 2) . '亿元</span>';

                //深圳成指数
                $url = "http://hq.sinajs.cn/list=s_sz399001";
                $str = file_get_contents($url);
                $str = iconv('GB2312//IGNORE', 'UTF-8', $str);
                $str = str_ireplace('var hq_str_s_sz399001="', "", $str);
                $str = str_ireplace('";', "", $str);
                $arr = explode(",", $str);
                if (round($arr[2], 2) < 0) {
                    $style = '<span class="xinsu-fontcolor-green">';
                } else {
                    $style = '<span class="xinsu-fontcolor-red">';
                }
                $zhishu .= '&nbsp;&nbsp;&nbsp;' . $arr[0] . '：' . $style . round($arr[1], 2) . '&nbsp;&nbsp;&nbsp;' . round($arr[2], 2) . '&nbsp;&nbsp;&nbsp;' . $arr[3] . '%</span>&nbsp;&nbsp;&nbsp;<span>' . round($arr[5] / 10000, 2) . '亿元</span>';

                $result["zhishu"] = $_SESSION["zhishu"] = $zhishu;
            } else {
                $result["zhishu"] = $_SESSION["zhishu"];
            }
        }

        //返回结果集
        ajax_return(1, "success", $result);
    }

    /**
     * 分配变量
     * @param string	$key 	标签名
     * @param mix	 	$val 	变量值
     */
    protected function assign($key, $val){
        if($key && preg_match('/^[A-z_][A-z0-9_]*$/', $key)){
            $this->_data[$key] = $val;
        } else{
            exit('变量名不合法：' . $key);
        }
    }

    /**
     * 页面输出
     */
    protected function display($html = ''){
        //移动设备
        if (is_mobile() && $this->_module == "home") {
            $module = "mobile";
        } else {
            $module = $this->_module;
        }

        //视图文件
        if(! $html){
            $html = APPPATH . 'view/' . $module . '/' . $this->_controller . '/' . $this->_action . '.html';
        } else{
            $html = APPPATH . 'view/' . $module . '/' . $html . '.html';
        }
        //加载模板
        $tpl = new Template($html);
        $runtime = intval((microtime(true) - BEGINTIME) * 1000);
        $this->assign("runtime", $runtime);
        $tpl->display($this->_data);
        exit;
    }

    /**
     * 判断开户账号是否访问了无权访问的菜单
     *
     * @return
     */
    protected function check_auth(){
        //0：超级管理员，1：普通管理员， 2：开户账号
        if(!isset($_SESSION["admin"]) || (isset($_SESSION["admin"]) && $_SESSION["admin"]["role_id"]!=2 )){
            return;
        }
        $auth_list = array(
            'user'=>array('index','add','edit','get_user_info','login'),
            'staff'=>array('index','add','edit'),
            'index'=>array('logout','clear_system_cache'),
            'sms'=>array('send','ajax_get_user_info')
        );
        $can_visit = false;
        foreach($auth_list as $key => $val){
            if($this->_controller == $key){
                if(array_key_exists($this->_action,array_flip($auth_list[$key]))){
                    $can_visit = true;
                    break;
                }
            }
        }
        if(!$can_visit){
            $this->error("无效的访问权限");
        }
    }

    /**
     * 错误页面输出
     */
    protected function error($msg = "") {
        $this->assign("msg", $msg);
        $this->display("/public/error");
    }
}
